#!/bin/bash
#
# GetX路由生成脚本（Shell版）
# 支持增量检测和强制全量生成

# 退出 immediately if a command exits with a non-zero status.
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color

# 参数解析
CLEAN=false
while getopts ":c" opt; do
  case $opt in
    c) CLEAN=true ;;
    \?) echo -e "${RED}Invalid option: -$OPTARG${NC}" >&2; exit 1 ;;
  esac
done

# 定位项目根目录
find_project_root() {
  local dir="$PWD"
  while [ "$dir" != "/" ]; do
    if [ -f "$dir/pubspec.yaml" ]; then
      echo "$dir"
      return
    fi
    dir=$(dirname "$dir")
  done
  echo -e "${RED}ERROR: Not in a Flutter project${NC}" >&2
  exit 1
}

ROOT_DIR=$(find_project_root)
cd "$ROOT_DIR"
echo -e "${CYAN}Project root: $ROOT_DIR${NC}"

# 执行构建
run_build() {
  local start_time=$(date +%s.%N)

  if $CLEAN; then
    echo -e "${MAGENTA}[INFO] Performing full rebuild...${NC}"
    dart run build_runner clean
    dart run build_runner build --delete-conflicting-outputs
  else
    if [ ! -f ".dart_tool/build/asset_graph.json" ]; then
      echo -e "${YELLOW}[INFO] First build or cache missing, performing safe full build...${NC}"
      dart run build_runner build --delete-conflicting-outputs
    else
      echo -e "${GREEN}[INFO] Performing incremental build...${NC}"
      dart run build_runner build
    fi
  fi

  local end_time=$(date +%s.%N)
  local elapsed=$(echo "$end_time - $start_time" | bc | awk '{printf "%.2f", $0}')
  echo -e "${CYAN}[SUCCESS] Build completed in ${elapsed}s${NC}"
}

# 验证输出
verify_output() {
  local route_table="lib/generated/route_table.dart"

  if [ -f "$route_table" ]; then
    echo -e "${GREEN}[SUCCESS] Route table generated: $route_table${NC}"
  else
    echo -e "${YELLOW}[WARNING] No route table detected${NC}"
    echo "Possible solutions:"
    echo "1. Check if any Dart files have @GetXRoute annotations"
    echo "2. Run with clean option: ./generate_routes.sh -c"
    echo "3. Check build.yaml configuration"
    exit 1
  fi
}

# 主流程
run_build
verify_output

exit 0